import { TransferProps } from 'antd';

import { TableTransfer, TableTransferProps } from '@/components/base/TableTransfer';
import { NODE_TYPE } from '@/constants/config';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';
import { useMode } from '@/store/mode';

const filterOption = (input: string, item: VariableItem) => {
  const upperInput = input.toUpperCase();
  return item.varLabel?.toUpperCase()?.includes(upperInput) || item.varName?.toUpperCase()?.includes(upperInput) || false;
};

export const Output = memo(() => {
  const [targetKeys, setTargetKeys] = useState<TransferProps['targetKeys']>([]);
  const { mode } = useMode();
  const { fieldTypeMap } = useDictStore();
  const { currentAndParentPrivateVariables, currentAndParentPublicVariables } = useCurrentNode<NODE_TYPE.END>();

  const dataSource = useMemo(() => {
    const variables = currentAndParentPrivateVariables.concat(currentAndParentPublicVariables);
    return variables.map((item) => {
      return {
        key: item.varName,
        ...item
      };
    });
  }, [currentAndParentPrivateVariables, currentAndParentPublicVariables]);

  const onChange: TableTransferProps['onChange'] = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys);
  };

  const columns: TableTransferProps['leftColumns'] = useMemo(() => {
    return [
      {
        dataIndex: 'varName',
        title: '变量名'
      },
      {
        dataIndex: 'varLabel',
        title: '变量中文名'
      },
      {
        dataIndex: 'varType',
        title: '类型',
        render(value) {
          return fieldTypeMap[value];
        }
      }
    ];
  }, [fieldTypeMap]);

  return (
    <div>
      <TableTransfer
        titles={[<span className="text-14--bold">变量列表</span>, <span className="text-14--bold">输出变量列表</span>]}
        dataSource={dataSource}
        targetKeys={targetKeys}
        disabled={mode === 'view'}
        showSearch
        tableRowKey="varName"
        showSelectAll={false}
        onChange={onChange}
        filterOption={filterOption}
        leftColumns={columns}
        rightColumns={columns}
      />
    </div>
  );
});
